<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item field="value2" label="客户名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading3"
                                @search="handleSearch3" v-model="pageData.kehumingcheng" :filter-option="false"
                                allow-clear allow-search @focus="focusSel3">
                                <a-option v-for="item in pageData.kehumingchenglist" :value="item">{{ item }}</a-option>
                            </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.kehumingcheng"
                @press-enter="huiche"
              />
            </a-form-item>

            <!-- <a-form-item field="value1" label="织造序号">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.zhizaocode"
                @press-enter="huiche"
              />
            </a-form-item> -->

            <a-form-item field="value3" label="织布单号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading3"
                                @search="handleSearch3" v-model="pageData.jihuaCode" :filter-option="false"
                                allow-clear allow-search @focus="focusSel9">
                                <a-option v-for="item in pageData.jihuaCodelist" :value="item">{{ item }}</a-option>
                            </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.jihuaCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item field="value1" label="坯布批次">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.greyBatchNo"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item field="value1" label="坯布编号">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.greyCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item field="rawmaterial" label="原料信息">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.rawmaterial"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item field="value1" label="订单交期">
              <a-date-picker
                popup-container="html"
                :style="{ width: '200px' }"
                @press-enter="huiche"
                class="bacClass"
                v-model="pageData.dingdan"
              />
            </a-form-item>

            <a-form-item field="value2" label="开单日期">
              <a-date-picker
                popup-container="html"
                :style="{ width: '200px' }"
                @press-enter="huiche"
                class="bacClass"
                v-model="pageData.kaidan"
              />
            </a-form-item>
            <a-form-item field="jindu" label="进度查询">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '200px' }"
                v-model="pageData.jindu"
                :options="pageData.jinduList"
              />
            </a-form-item>
            <a-form-item label="生产时间" field="productDate">
              <a-range-picker
                popup-container="html"
                style="width: 270px"
                class="bacClass"
                v-model="pageData.productDate"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          class="gesture"
          :items="pageData.btnList"
          @select="selectHandler"
          @export="exports"
          @exportAll="exportAll"
          @fhzy="fhzy"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <!--
                        表格插件
                    -->
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          style="height: 100%"
          :suppressDragLeaveHidesColumns="true"
          rowSelection="multiple"
          @grid-ready="gridReady"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tableColumns"
          :localeText="localeText1"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
          @columnVisible="onColumnVisible"
          @FilterChanged="FilterChangeds"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      :page-size="size"
      :current="page"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="编号"
            field="brandCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              class="bacClass"
              placeholder=""
              v-model="dataForm.brandCode"
              @blur="inputBlur"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="品牌名称"
            field="brandName"
            :rules="[{ required: true, message: '品牌名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandName" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="布类类型"
            field="clothClass"
            :rules="[{ required: true, message: '布类类型必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loading"
              placeholder=""
              @search="handleSearch1"
              v-model="dataForm.clothClass"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusSel1"
            >
              <a-option v-for="item in pageData.typeList" :value="item">{{ item }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <!-- <a-input v-model="dataForm.remark" /> -->
            <a-textarea
              class="bacClass"
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts" setup>
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { baseURL } from '../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import { FormInstance } from '@arco-design/web-vue/es/form'
import validate from '@/hooks/useValidate'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import { localeText } from '@/api/aggridZw'
// 引入
import setTableTotalRow from '@/utils/setTableTotalRow.ts'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { stringify } from 'qs'
import { pagingList } from '@/api/paging'
import dayjs from 'dayjs'
interface BrandInfo {
  id: any
  brandCode: string
  brandName: string
  clothClass: string
  remark: string
  deleteState: number | string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  console.log(val)

  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}
const headerShow = ref<boolean>(true)
const toFixedNum = (num: number) => {
  return parseFloat(num.toFixed(2))
}
function doRefresh() {
  pageData.pageLoading = true
  updateGridState01()
  post({
    url: '/product/statement/getProductionInfo',
    data: {
      customName:pageData.kehumingcheng,
      planOrderCode:pageData.jihuaCode,
      weavDeliveryDate:pageData.dingdan,
      planDate:pageData.kaidan,
      orderState:pageData.jindu,
      greyBatchNo:pageData.greyBatchNo,
      productStartDate:pageData.productDate ? pageData.productDate[0] : '',
      productEndDate:pageData.productDate ? pageData.productDate[1] : '',
      rawmaterial:pageData.rawmaterial,
      page: page.value, 
      size: size.value
    }
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        if (data.list.length != 0) {
          total.value = data.total
        } else {
          total.value = 0
        }
        // 查询方法改
        gridOption.value.setFilterModel(null)
        gridOption.value.setRowData(data.list)
        setTableTotalRow(gridOption, data.list, [
          'noPosteriorWeight',
          'greyOutNum',
          'orderWeight',
          'actualWeight',
          'greyInNum',
          'posteriorWeight',
          'badWeight',
          'greyInWeight',
          'noHorseNum',
          'noGreyInNum',
          'inventoryWeight',
          'noIntoWeight',
          'sgcNum',
          'greyOutWeight',
          'badGreyInNum',
          'csNum',
          'croppingWeight',
          'noGreyInWeight',
          'stockWeight',
          'stockNum',
          'csWeight',
          'pieceNum',
          'badGreyInWeight',
        ])
        // pageData.hejishuzu = []
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const { selectedRowKeys, onSelectionChange } = useRowSelection()
const pagination = usePagination(doRefresh)
const table = useTable()
const rowKey = useRowKey('id')
const tableColumns: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  {
    headerName: '颜色',
    field: 'colorName',
    width: 150,
  },
  {
    headerName: '原料信息',
    field: 'rawmaterial',
    width: 150,
  },
  {
    headerName: '未完成重量',
    field: 'noPosteriorWeight',
    width: 150,
  },
  {
    headerName: '开机机台数',
    field: 'machineNum',
    width: 150,
  },
  {
    headerName: '指令重量',
    field: 'orderWeight',
    width: 150,
  },
  {
    headerName: '备注',
    field: 'remark',
    width: 150,
  },
  {
    headerName: '坯布名称',
    field: 'greyName',
    width: 150,
  },
  {
    headerName: '订单状态',
    field: 'planOrderState',
    cellRenderer: {
      template: `
                    <a-tag color="blue" v-if="a==0">待排产</a-tag>
                    <a-tag color="blue" v-if="a==1">已排产</a-tag>
                    <a-tag color="blue" v-if="a==2">生产中</a-tag>
                    <a-tag color="blue" v-if="a==3">完成</a-tag>
                    <a-tag color="blue" v-if="a==4">暂停</a-tag>
                    <a-tag color="blue" v-if="a==5">委外订单</a-tag>
                    `,
      setup(props: any) {
        return {
          a: props.params.data.planOrderState,
        }
      },
    },
    filterParams: {
    valueFormatter: function (params: any) {
      return params.value == 0
        ? '待排产'
        : params.value == 1
        ? '已排产'
        : params.value == 2
        ? '生产中'
        : params.value == 3
        ? '完成'
        : params.value == 4
        ? '暂停'
        : params.value == 5
        ? '已排产'
        : ''
    },
  },
    width: 150,
  },
  {
    headerName: '客户订单号',
    field: 'customOrderNo',
    width: 150,
  },
  {
    headerName: '是否加急',
    field: 'urgentState',
    width: 150,
  },
  {
    headerName: '公司',
    field: 'firm',
    width: 150,
  },
  {
    headerName: '织造交期',
    field: 'weavDeliveryDate',
    width: 150,
  },
  {
    headerName: '验后重量',
    field: 'posteriorWeight',
    width: 150,
  },
  {
    headerName: '入库匹数',
    field: 'greyInNum',
    width: 150,
  },
  {
    headerName: '指令匹数',
    field: 'pieceNum',
    width: 150,
  },
  {
    headerName: '订单针筒',
    field: 'workDrum',
    width: 150,
  },
  {
    headerName: '加工单位',
    field: 'outSouringCompany',
    width: 150,
  },
  {
    headerName: '入次匹数',
    field: 'badGreyInNum',
    width: 150,
  },
  {
    headerName: '入次重量',
    field: 'badGreyInWeight',
    width: 150,
  },
  {
    headerName: '落布匹数',
    field: 'csNum',
    width: 150,
  },
  {
    headerName: '验后匹数',
    field: 'sgcNum',
    width: 150,
  },
  {
    headerName: '坯布批次',
    field: 'greyBatchNo',
    width: 150,
  },
  {
    headerName: '磅布重量',
    field: 'croppingWeight',
    width: 150,
  },
  {
    headerName: '未完成匹数',
    field: 'noHorseNum',
    width: 150,
  },
  {
    headerName: '克重',
    field: 'weight',
    width: 150,
  },
  {
    headerName: '客户名称',
    field: 'customName',
    width: 150,
  },
  {
    headerName: '坯布编号',
    field: 'greyCode',
    width: 150,
  },
  {
    headerName: '开单日期',
    field: 'planDate',
    width: 150,
  },
  {
    headerName: '是否抽针',
    field: 'drawnNeedleState',
    width: 150,
  },
  {
    headerName: '开单人',
    field: 'tabulationPerson',
    width: 150,
  },
  {
    headerName: '次布重量',
    field: 'badWeight',
    width: 150,
  },
  {
    headerName: '门幅',
    field: 'width',
    width: 150,
  },
  {
    headerName: '开机机台',
    field: 'machines',
    width: 150,
  },
  {
    headerName: '时间',
    field: 'time',
    width: 150,
  },
  {
    headerName: '织布单号',
    field: 'planOrderCode',
    width: 150,
  },
  {
    headerName: '订单性质',
    field: 'businessType',
    width: 150,
  },
  {
    headerName: '入库重量',
    field: 'greyInWeight',
    width: 150,
  },
  {
    headerName: '未入库匹数',
    field: 'noGreyInNum',
    width: 150,
  },
  {
    headerName: '未入库重量',
    field: 'noGreyInWeight',
    width: 150,
  },
  {
    headerName: '出库匹数',
    field: 'greyOutNum',
    width: 150,
  },
  {
    headerName: '出库重量',
    field: 'greyOutWeight',
    width: 150,
  },
  {
    headerName: '库存重量',
    field: 'stockWeight',
    width: 150,
  },
  {
    headerName: '库存匹数',
    field: 'stockNum',
    width: 150,
  },
  {
    headerName: '昨日产量',
    field: 'csWeight',
    width: 150,
  },
]
const pageData = reactive<{
  showAdd: boolean
  sideTitle: string
  dropDownData: any
  nameList: []
  pageLoading: boolean
  typeList: []
  dropDownData1: any
  rHeight: any
  btnList: any[]
  isEdit: boolean
  zhizaocode: any
  zhizaocodelist: any[]
  hejishuzu: []
  pibubianhao: any
  pibubianhaolist: []
  pibumingcheng: any
  pibumingchenglist: []
  kehumingcheng: any
  kehumingchenglist: any[]
  jianyanriqi: any
  jitaihao: any
  jitaihaolist: []
  firmId2: any
  firmList2: []
  yuangongName: []
  jihuaCode: any
  jihuaCodelist: any[]
  dingdan: any
  kaidan: any
  jindu: any
  jinduList: any
  greyBatchNo: any
  productDate:any[]
  greyCode:any
  rawmaterial:any
}>({
  rawmaterial:'',
  greyCode:'',
  nameList: [],
  showAdd: false,
  sideTitle: '新增品牌资料',
  dropDownData: '',
  pageLoading: false,
  typeList: [],
  dropDownData1: '',
  rHeight: 0,
  btnList: [],
  isEdit: false,
  zhizaocode: '',
  zhizaocodelist: [] as any,
  hejishuzu: [],
  pibubianhao: '',
  pibubianhaolist: [],
  pibumingcheng: '',
  pibumingchenglist: [],
  kehumingcheng: '',
  kehumingchenglist: [] as any,
  jianyanriqi: '',
  jitaihao: '',
  jitaihaolist: [],
  firmId2: '',
  firmList2: [],
  yuangongName: [],
  jihuaCode: '',
  jihuaCodelist: [] as any,
  dingdan: '',
  kaidan: '',
  jindu: 0,
  jinduList: [
    { label: '全部', value: 0 },
    { label: '未完成', value: 1 },
    { label: '已完成', value: 2 },
  ],
  greyBatchNo: '',
  productDate:[]
})

interface gcType {
  id: any
  company: any
}

//下拉框得到焦点
const focusSel = () => {
  selCxAll({ brandName: '', deleteState: 0 })
}
//下拉数据

onMounted(() => {
  // pageData.dingdan = dayjs(new Date()).format('YYYY-MM-DD')
  pageData.kaidan = dayjs(new Date()).format('YYYY-MM-DD')
  doRefresh()
  // 切换tap到本页面执行的方法
  emitter.on('BrandInfo', () => {
    // selCxAll1({});
    doRefresh()
  })
})
let cxbl = ''
//查询
const selectHandler = () => {
  pagination.page = 1
  cxbl = pageData.dropDownData
  doRefresh()
}
const queryData = reactive({
  clothType: '',
})
const addHandler = () => {}
const dataForm = reactive<BrandInfo>({
  id: null,
  remark: '',
  brandName: '',
  clothClass: '',
  deleteState: '',
  createName: '',
  createTime: '',
  updateName: '',
  updateTime: '',
  brandCode: '',
})

// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

let formRef = ref<FormInstance>()
const sideOk = () => {
  formRef.value?.validate().then((err) => {
    if (!err) {
      formRef.value?.validate().then((err) => {
        if (!err) {
          pageData.pageLoading = true
          if (pageData.sideTitle === '新增品牌资料') {
            post({
              url: 'product/Brand/insert',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                doRefresh()
                pageData.pageLoading = false
              })
          } else {
            post({
              url: 'product/Brand/update',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                doRefresh()
                pageData.pageLoading = false
              })
          }
        }
      })
    }
  })
}
const deleteHandler = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }

  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      pageData.pageLoading = true
      post({
        url: 'product/Brand/deleteList',
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return o.id
        }),
      })
        .then(({ code, data }: any) => {
          if (code === 200) {
            Message.success({
              content: '删除成功',
              duration: 5000,
            })
            pagination.page = 1
            doRefresh()
          } else {
            Message.error({
              content: '删除失败',
              duration: 5000,
            })
          }
        })
        .finally(() => {
          pageData.pageLoading = false
        })
    },
  })
}

let curobj = null
const editHandler = (record: BrandInfo) => {
  curobj = record
  selCxAll({ key: '' })
  dataForm.brandCode = record.brandCode
  dataForm.brandName = record.brandName
  dataForm.clothClass = record.clothClass
  dataForm.remark = record.remark
  dataForm.id = record.id
  pageData.sideTitle = '修改品牌资料'
  pageData.showAdd = true
}
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
  return new Promise<void>((resolve) => {
    if (window.encodeURI(value).indexOf('%') !== -1) {
      cb('填写的值不能包含中文！')
    }
    resolve()
  })
}
//input离开焦点 将小写转大写
const inputBlur = () => {
  dataForm.brandCode = dataForm.brandCode.toUpperCase()
}
//导出
const exports = () => {
  //
  var zongshuzu = [] as any
  gridOption.value.getSelectedRows().forEach(function (o: any) {
    zongshuzu.push(o)
  })
  // pageData.hejishuzu.forEach((o: any) => {
  //   zongshuzu.push(o)
  // })
  localStorage.setItem('daocu', JSON.stringify(zongshuzu))
  //
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  } else {
    let idList: any = []
    // gridOption.value.getSelectedRows().forEach(function(o:any){
    //     idList.push(o['id'])
    // })
    zongshuzu.forEach(function (o: any) {
      idList.push(o['id'])
    })

    //将表头拼接出来
    let head =
      '<th>颜色</th><th>原料信息</th><th>未完成重量</th><th>开机机台数</th><th>指令重量</th><th>备注</th><th>坯布名称</th><th>订单状态</th><th>客户订单号</th><th>是否加急</th><th>公司</th>'
    head +=
      '<th>织造交期</th><th>验后重量</th><th>入库匹数</th><th>指令匹数</th><th>订单针筒</th><th>加工单位</th><th>入次匹数</th><th>落布匹数</th><th>验后匹数</th><th>坯布批次</th><th>磅布重量</th><th>未完成匹数</th><th>克重</th><th>客户名称</th><th>坯布编号</th><th>开单日期</th><th>是否抽针</th>'
    head +=
      '<th>开单人</th><th>次布重量</th><th>门幅</th><th>开机机台</th><th>时间</th><th>织布单号</th><th>订单性质</th><th>入库重量</th><th>未入库匹数</th><th>未入库重量</th><th>出库匹数</th><th>出库重量</th><th>库存重量</th><th>库存匹数</th><th>昨日产量</th>'
    //拿到当前表格数据与勾选的行做筛选

    // let nowRow = table.dataList.filter(function (o) {
    //     return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
    // })
    // let nowRow = zongshuzu.filter(function (o) {
    //   return (
    //     zongshuzu
    //       .map((o: any) => {
    //         return o.id
    //       })
    //       .indexOf(o['id']) !== -1
    //   )
    // })
    let nowRow = zongshuzu.filter((item: any) => item.id)
    let body = ''
    var zlzhongliang = 0
    var pishu = 0
    var luobuzhongliang = 0
    var yhzhongliang = 0
    var yhpishu = 0
    var wwczhongliang = 0
    var wwcpishu = 0
    var ztchangliang = 0
    var rkzhongliang = 0
    var rkpishu = 0
    var wrkzhongliang = 0
    var wrkpishu = 0
    var cibuzhongliang = 0
    var ckzhongliang = 0
    var ckpishu = 0
    var kucunzhongliang = 0
    var kucunpishu = 0
    nowRow.forEach(function (o: any, index: any) {
      if (o['planOrderState'] == 0) {
        o['planOrderState'] = '待排产'
      } else if (o['planOrderState'] == 1) {
        o['planOrderState'] = '已排产'
      } else if (o['planOrderState'] == 2) {
        o['planOrderState'] = '生产中'
      } else if (o['planOrderState'] == 3) {
        o['planOrderState'] = '完成'
      } else if (o['planOrderState'] == 4) {
        o['planOrderState'] = '暂停'
      } else if (o['planOrderState'] == 5) {
        o['planOrderState'] = '委外订单'
      }
      if (index != nowRow.length - 1) {
        zlzhongliang = zlzhongliang + o['orderWeight']
        pishu = pishu + o['orderWeight']
        luobuzhongliang = luobuzhongliang + o['actualWeight']
        yhzhongliang = yhzhongliang + o['posteriorWeight']
        yhpishu = yhpishu + o['horseNum']
        wwczhongliang = wwczhongliang + o['noPosteriorWeight']
        wwcpishu = wwcpishu + o['noHorseNum']
        ztchangliang = ztchangliang + o['horseNum']
        rkzhongliang = rkzhongliang + o['intoWeight']
        rkpishu = rkpishu + o['intoPiecesNum']
        wrkzhongliang = wrkzhongliang + o['noIntoWeight']
        wrkpishu = wrkpishu + o['noHorseNum']
        cibuzhongliang = cibuzhongliang + o['fabricWeight']
        ckzhongliang = ckzhongliang + o['outWeight']
        ckpishu = ckpishu + o['outPiecesNum']
        kucunzhongliang = kucunzhongliang + o['inventoryWeight']
        kucunpishu = kucunpishu + o['inventoryPiecesNum']
      } else {
        o['orderWeight'] = zlzhongliang
        o['orderWeight'] = pishu
        o['actualWeight'] = luobuzhongliang
        o['posteriorWeight'] = yhzhongliang
        o['horseNum'] = yhpishu
        o['noPosteriorWeight'] = wwczhongliang
        o['noHorseNum'] = wwcpishu
        o['horseNum'] = ztchangliang
        o['intoWeight'] = rkzhongliang
        o['intoPiecesNum'] = rkpishu
        o['noIntoWeight'] = wrkzhongliang
        o['noHorseNum'] = wrkpishu
        o['fabricWeight'] = cibuzhongliang
        o['outWeight'] = ckzhongliang
        o['outPiecesNum'] = ckpishu
        o['inventoryWeight'] = kucunzhongliang
        o['inventoryPiecesNum'] = kucunpishu
      }
      body += '<tr><td>' + o['colorName'] + '</td>'
      body += '<td>' + o['rawmaterial'] + '</td>'
      body += '<td>' + o['noPosteriorWeight'] + '</td>'
      body += '<td>' + o['machineNum'] + '</td>'
      body += '<td>' + o['orderWeight'] + '</td>'
      body += '<td>' + o['remark'] + '</td>'
      body += '<td>' + o['greyName'] + '</td>'
      body += '<td>' + o['planOrderState'] + '</td>'
      body += '<td>' + o['customOrderNo'] + '</td>'
      body += '<td>' + o['urgentState'] + '</td>'
      body += '<td>' + o['firm'] + '</td>'
      body += '<td>' + o['weavDeliveryDate'] + '</td>'
      body += '<td>' + o['posteriorWeight'] + '</td>'
      body += '<td>' + o['greyInNum'] + '</td>'
      body += '<td>' + o['pieceNum'] + '</td>'
      body += '<td>' + o['workDrum'] + '</td>'
      body += '<td>' + o['outSouringCompany'] + '</td>'
      body += '<td>' + o['badGreyInNum'] + '</td>'
      body += '<td>' + o['csNum'] + '</td>'
      body += '<td>' + o['sgcNum'] + '</td>'
      body += '<td>' + o['greyBatchNo'] + '</td>'
      body += '<td>' + o['croppingWeight'] + '</td>'
      body += '<td>' + o['noHorseNum'] + '</td>'
      body += '<td>' + o['weight'] + '</td>'
      body += '<td>' + o['customName'] + '</td>'
      body += '<td>' + o['greyCode'] + '</td>'
      body += '<td>' + o['planDate'] + '</td>'
      body += '<td>' + o['drawnNeedleState'] + '</td>'
      body += '<td>' + o['tabulationPerson'] + '</td>'
      body += '<td>' + o['badWeight'] + '</td>'
      body += '<td>' + o['width'] + '</td>'
      body += '<td>' + o['machines'] + '</td>'
      body += '<td>' + o['time'] + '</td>'
      body += '<td>' + o['planOrderCode'] + '</td>'
      body += '<td>' + o['businessType'] + '</td>'
      body += '<td>' + o['greyInWeight'] + '</td>'
      body += '<td>' + o['noGreyInNum'] + '</td>'
      body += '<td>' + o['noGreyInWeight'] + '</td>'
      body += '<td>' + o['greyOutNum'] + '</td>'
      body += '<td>' + o['greyOutWeight'] + '</td>'
      body += '<td>' + o['stockWeight'] + '</td>'
      body += '<td>' + o['stockNum'] + '</td>'
      body += '<td>' + o['csWeight'] + '</td>'
      body += '</tr>'
    })
    tableToXlsx(head, '生产进度查询表', body)
    console.log(table)
  }
}

const exportAll = () => {
  var obj = {}
  if (pageData.kehumingcheng != '') {
    obj['customName'] = pageData.kehumingcheng
  }
  if (pageData.zhizaocode != '') {
    obj['weaveCode'] = pageData.zhizaocode
  }
  if (pageData.jihuaCode != '') {
    obj['planOrderCode'] = pageData.jihuaCode
  }
  if (pageData.dingdan != '') {
    obj['weavDeliveryDate'] = pageData.dingdan
  }
  if (pageData.kaidan != '') {
    obj['planDate'] = pageData.kaidan
  }
  post({
    url: '/product/statement/exportGetProductionInfo',
    data: obj,
    responseType: 'blob',
  }).then((res: any) => {
    filedownload(res, '生产进度查询.xlsx')
  })
}
function tableToXlsx(head: any, filename: any, body: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
    template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = filename
  a.click()
  document.removeChild(a)
}

//模板下载
const downloadHandler = () => {
  axios
    .get(baseURL + '/product/Brand/uploadModel', {
      responseType: 'blob',
      headers: {
        token: sessionStorage.getItem('USER-TOKEN-KEY'),
      },
    })
    .then((res) => {
      if (res.status === 200) {
        filedownload(res.data, '品牌资料.xlsx')
      }
    })
}
//导入
const importHandler = () => {
  const inputEle: HTMLInputElement = document.createElement('input')
  inputEle.type = 'file'
  inputEle.id = 'fileUploadExcel'
  inputEle.accept =
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
  inputEle.addEventListener('change', (e) => {
    const formData = new FormData()
    if (inputEle.files !== null) {
      formData.append('file', inputEle.files[0] || '')
    } else {
      Message.warning('未选择文件！')
      return
    }
    pageData.pageLoading = true
    axios
      .post(baseURL + '/product/Brand/importModelData', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          token: sessionStorage.getItem('USER-TOKEN-KEY'),
        },
      })
      .then((result) => {
        if (result.data['code'] === 200) {
          Message.success('导入成功')
        } else {
          Message.error(result.data.message)
        }
      })
      .finally(() => {
        pageData.pageLoading = false
        doRefresh()
      })
  })
  inputEle.click()
}
//下拉数据
const options = ref<any>(pageData.pibubianhaolist)
const loading = ref(false)
const handleSearch1 = (value: any) => {
  if (value) {
    const ob = { greyCode: value }
    loading.value = true

    selCxAll(ob)
    options.value = pageData.pibubianhaolist
    loading.value = false
  } else {
    options.value = []
  }
}

//下拉框查询 布料类型
//下拉框查询 坯布编号
function selCxAll(val: any) {
  post({
    url: 'product/Rawmaterial/getGreyDrop',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      // (data as string[]).splice(0, 0, "全部");
      pageData.pibubianhaolist = data
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}

const options2 = ref<any>(pageData.pibumingchenglist)
const loading2 = ref(false)
const handleSearch2 = (value: any) => {
  if (value) {
    const ob = { grayFabricName: value }
    loading.value = true

    selCxAll2(ob)
    options.value = pageData.pibumingchenglist
    loading.value = false
  } else {
    options.value = []
  }
}
//下拉框查询 坯布名称
function selCxAll2(val: any) {
  post({
    url: 'product/Rawmaterial/getGreyDrop',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      // (data as string[]).splice(0, 0, "全部");
      pageData.pibumingchenglist = data
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}
const options3 = ref<any>(pageData.kehumingchenglist)
const loading3 = ref(false)
const handleSearch3 = (value: any) => {
  if (value) {
    const ob = { customName: value }
    loading.value = true

    selCxAll3(ob)
    options.value = pageData.kehumingchenglist
    loading.value = false
  } else {
    options.value = []
  }
}
function selCxAll3(val: any) {
  post({
    url: 'planSingle/planOrder/getDropInfo',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      // (data as string[]).splice(0, 0, "全部");
      //sessionStorage.setItem("kehumingccheng",JSON.stringify(data))
      //sessionStorage.setItem("iskehupp",JSON.stringify(data))

      pageData.kehumingchenglist = data
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}

const options4 = ref<any>(pageData.jitaihaolist)
const loading4 = ref(false)
const handleSearch4 = (value: any) => {
  if (value) {
    const ob = { machineCode: value }
    loading.value = true

    selCxAll4(ob)
    options.value = pageData.jitaihaolist
    loading.value = false
  } else {
    options.value = []
  }
}
//下拉框查询 坯布名称
function selCxAll4(val: any) {
  post({
    url: 'planSingle/machine/getFieldValue',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      // (data as string[]).splice(0, 0, "全部");

      pageData.jitaihaolist = data
      //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}

function selCxAll8(val: any) {
  post({
    url: 'planSingle/planOrder/getDropInfo',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      // (data as string[]).splice(0, 0, "全部");

      pageData.zhizaocodelist = data
      //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}
function selCxAll9(val: any) {
  post({
    url: 'planSingle/planOrder/getDropInfo',
    data: val,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      // (data as string[]).splice(0, 0, "全部");

      pageData.jihuaCodelist = data
      //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}
//下拉框得到焦点
const focusSel1 = () => {
  selCxAll({ greyCode: '' })
}
const focusSel2 = () => {
  selCxAll2({ grayFabricName: '' })
}

const focusSel3 = () => {
  selCxAll3({ customName: '' })
}
const focusSel4 = () => {
  selCxAll4({ machineCode: '' })
}
const focusSel8 = () => {
  selCxAll8({ weaveCode: '' })
}
const focusSel9 = () => {
  selCxAll9({ planOrderCode: '' })
}
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

// if (permissionStore.hasPermisson('ppzl.cx')) {
// }
pageData.btnList.push('查询')

pageData.btnList.push('导出')
pageData.btnList.push('全部导出')

// if (permissionStore.hasPermisson('ppzl.dr')) {
//   pageData.btnList.push('返回主页')
// }
if (permissionStore.hasPermisson('ppzl.xg')) {
  pageData.isEdit = true
}
const handleChange = (_data: any) => {
  table.handleSuccess(_data)
}
const fhzy = () => {
  emit('takebiaoji', 0)
}
//获得公司部门组下的员工
const getFirmGroup = () => {
  get({
    url: '/org/firmGroup/getTreeFirmGroup',
  }).then(({ code, data }) => {
    if (code === 200) {
      pageData.firmList2 = data
      huoquyuangong()
    }
  })
}
const huoquyuangong = () => {
  pageData.firmList2.forEach((o: any) => {
    o.children.forEach((d: any) => {
      d.children.forEach((a: any) => {
        post({
          url: 'org/employee/getList',
          data: {
            groupId: a.value,
            empName: '',
          },
        }).then((res) => {
          if (res.code == 200) {
            res.data.forEach((m: any) => {
              a.children = [{ label: m.empName, value: m.empName }]
            })
          } else {
            Message.error({
              content: '查询员工名称失败',
              duration: 5000,
            })
          }
        })
      })
    })
  })
}
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}
const localeText1: any = ref(localeText)
const huiche = () => {
  doRefresh()
}
const pagingList1: any = ref(pagingList)

const FilterChangeds = (params: any) => {
  let data: any = {
    data: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.data.push(row.data)
  })
  setTableTotalRow(gridOption, data.data, [
    'noPosteriorWeight',
    'greyOutNum',
    'orderWeight',
    'actualWeight',
    'greyInNum',
    'posteriorWeight',
    'badWeight',
    'greyInWeight',
    'noHorseNum',
    'noGreyInNum',
    'inventoryWeight',
    'noIntoWeight',
    'sgcNum',
    'greyOutWeight',
    'badGreyInNum',
    'csNum',
    'croppingWeight',
    'noGreyInWeight',
    'stockWeight',
    'stockNum',
    'csWeight',
    'pieceNum',
    'badGreyInWeight',
  ])
}

const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('productionInfo-1', gridOption, colState, tableColumns)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
const onColumnVisible = () => {
    saveGridState01()
}
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
